import { defineStore } from 'pinia'
import Notifier from 'src/helpers/Notifier'
import {api} from "boot/axios";
import {Doctor} from "src/models/doctor";
import {toRaw} from "vue";

const preferredShiftTranslationPathMap = {
  night: 'Ночь',
  day: 'День'
}

export const doctorsStore = defineStore('doctors', {
  state: () => ({
    doctorsList: [],
    availableModalities: [],
    shiftTypes: [],
    scheduleTypes: [],
    editableDoctor: null,
    isEditing: false,
    creatableDoctor: null,
    isCreating: false
  }),

  getters: {
  },

  actions: {
    async getDoctorsList() {
      try {
        const response = await api.get('/doctors') ?? []
        this.doctorsList = response.data.map((el) => new Doctor(el))

        return this.doctorsList
      } catch (err) {
        Notifier.error('Ошибка при загрузке списка пользователей')
        console.error(err)
        return err
      }
    },
    async createDoctor(payload) {
      try {
        console.log('payload', toRaw(payload))
        const normalizedPayload = {
          create_user_schema: {
            email: payload.user.email,
            full_name: payload.user.full_name,
            password: payload.user.password
          },
          main_modality_code: payload.main_modality.code,
          additional_modalities_codes: payload.additional_modalities.map((el) => el.code),
          rate_percent: payload.rate_percent,
          preferred_schedule: payload.preferred_schedule.value,
          preferred_shift: payload.preferred_shift.value
        }

        const response = await api.post('/doctors', normalizedPayload)
        this.doctorsList.push(new Doctor(response.data))

        Notifier.success('Пользователь успешно создан')

        return response.data
      } catch (err) {
        Notifier.error('Ошибка при создании пользователя')
        console.error(err)
        return err
      } finally {
        this.isCreating = false
      }
    },
    async updateDoctor(payload) {
      try {
        console.log('payload', toRaw(payload))
        const normalizedPayload = {
          update_user_schema: {
            email: payload.user.email,
            full_name: payload.user.full_name,
            password: payload.password,
            new_password: payload.newPassword
          },
          main_modality_code: payload.main_modality.code,
          additional_modalities_codes: payload.additional_modalities.map((el) => el.code),
          rate_percent: payload.rate_percent,
          preferred_schedule: payload.preferred_schedule.value,
          preferred_shift: payload.preferred_shift.value
        }

        const response = await api.put(`/doctors/${payload.id}`, normalizedPayload)

        await this.getDoctorsList()

        Notifier.success('Пользователь успешно обновлен')

        return response.data
      } catch (err) {
        Notifier.error('Ошибка при обновлении пользователя')
        console.error(err)
        return err
      } finally {
        this.isEditing = false
      }
    },
    async getAdditionalModalities() {
      try {
        const response = await api.get('/doctors/modalities/')

        this.availableModalities = response.data

        return this.availableModalities
      } catch (err) {
        Notifier.error('Ошибка при получении списка специализаций')
        console.error(err)
        return err
      }
    },
    async getOneDoctor(payload) {
      try {
        const response = await api.get(`/doctors/${payload}/`)

        return new Doctor(response.data)
      } catch (err) {
        Notifier.error('Ошибка при получении профиля доктора')

        console.error(err)
        return err
      }
    },
    async deleteDoctor(payload) {
      try {
        const response = await api.delete(`/doctors/${payload}/`)
        await this.getDoctorsList()
        Notifier.success('Профиль врача успешно удален')

        return response.data
      } catch (err) {
        Notifier.error('Ошибка при удалении профиля доктора')

        console.error(err)
        return err
      }
    },
    async getShiftTypes() {
      try {
        const response = await api.get('/doctors/shift-types/')

        this.shiftTypes = response.data.map((el) => {
          return {
            value: el,
            label: preferredShiftTranslationPathMap[el]
          }
        })
      } catch (err) {
        console.error(err)
        return err
      }
    },
    async getScheduleTypes() {
      try {
        const response = await api.get('/doctors/schedule-types/')

        this.scheduleTypes = response.data.map((el) => {
          return {
            value: el,
            label: el
          }
        })
      } catch (err) {
        console.error(err)
        return err
      }
    }
  }
})
